

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Layout from '../../components/Layout';
import authApi from '../../api/auth';

interface UserProfile {
  id: number;
  gender: string | null;
  avatar: string;
  address: string | null;
  email: string | null;
  userId: number;
  nickName: string;
  age: number | null;
}

interface UserInfo {
  id: number;
  username: string;
  profile: UserProfile;
  roles?: Array<{
    id: number;
    name: string;
    code: string;
  }>;
  currentRole?: {
    id: number;
    name: string;
    code: string;
  };
}

const PersonalCenter: React.FC = () => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 检查是否有token
      const token = localStorage.getItem('token');
      if (!token) {
        setError('需要登录才能访问个人中心');
        setLoading(false);
        return;
      }
      
      const response = await authApi.getUser();
      console.log('获取到的用户信息:', response);
      
      if (response && response.data) {
        setUserInfo(response.data);
      } else {
        setError('获取用户信息失败');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 检查是否是认证错误
      if (error instanceof Error && (error.message.includes('401') || error.message.includes('Unauthorized'))) {
        setError('登录已过期，请重新登录');
      } else {
        setError('获取用户信息失败，请重新登录');
      }
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时获取用户信息
  useEffect(() => {
    fetchUserInfo();
  }, []);

  const handleRecentCourseClick = (courseId: string) => {
    navigate(`/course-detail?courseId=${courseId}`);
  };

  return (
    <Layout title="个人中心 - 学途">
      <div className="flex min-h-screen bg-gray-50">
        {/* 左侧菜单 */}
        <aside className="w-64 bg-white border-r border-gray-200 min-h-screen">
          <nav className="p-4">
            {/* 个人中心菜单 */}
            <div>
              <Link to="/personal-center" className="flex items-center space-x-3 px-4 py-3 mb-4 bg-blue-50 text-blue-600 rounded-lg transition-colors">
                <i className="fas fa-user text-lg"></i>
                <span className="font-medium">个人中心</span>
              </Link>
              <ul className="space-y-1">
                <li>
                  <Link to="/personal-info" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-user-edit text-base"></i>
                    <span>个人信息</span>
                  </Link>
                </li>
                <li>
                  <Link to="/enrolled-courses" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-book-open text-base"></i>
                    <span>已报名课程</span>
                  </Link>
                </li>
                <li>
                  <Link to="/messages" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-envelope text-base"></i>
                    <span>站内信</span>
                  </Link>
                </li>
                <li>
                  <Link to="/account-security" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-shield-alt text-base"></i>
                    <span>账户安全</span>
                  </Link>
                </li>
              </ul>
            </div>
          </nav>
        </aside>

        {/* 主内容区域 */}
        <main className="flex-1 min-w-0">
          <div className="max-w-6xl mx-auto px-6 py-8">
            {/* 用户信息卡片 */}
            <div className="bg-white rounded-xl shadow-lg p-8 mb-8">
              {loading ? (
                <div className="flex justify-center items-center py-12">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
                  <span className="ml-3 text-gray-600">加载中...</span>
                </div>
              ) : error ? (
                <div className="text-center py-12">
                  <div className="text-red-500 mb-4">
                    <i className="fas fa-exclamation-triangle text-4xl"></i>
                  </div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
                  <p className="text-gray-600 mb-4">{error}</p>
                  <div className="flex justify-center space-x-3">
                    {error.includes('登录') ? (
                      <Link 
                        to="/login"
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        去登录
                      </Link>
                    ) : (
                      <button 
                        onClick={fetchUserInfo}
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        重试
                      </button>
                    )}
                  </div>
                </div>
              ) : userInfo ? (
                <div className="flex items-center space-x-6">
                  <img 
                    src={userInfo.profile?.avatar || "https://s.coze.cn/image/4yC-9u6pnQo/"} 
                    alt="用户头像" 
                    className="w-20 h-20 rounded-full border-4 border-white shadow-lg"
                  />
                  <div className="flex-1">
                    <h1 className="text-3xl font-bold text-gray-900">
                      {userInfo.profile?.nickName || userInfo.username || '用户'}
                    </h1>
                    <p className="text-gray-600 mt-1">学号: {userInfo.username}</p>
                    <p className="text-gray-600">
                      邮箱: {userInfo.profile?.email || '未设置'}
                    </p>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-blue-600">LV.3</div>
                    <div className="text-gray-600 text-sm">学习等级</div>
                  </div>
                </div>
              ) : null}
            </div>

            {/* 学习概览 */}
            <section className="mb-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">学习概览</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <div className="bg-white rounded-xl shadow-lg p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">已报名课程</p>
                      <p className="text-3xl font-bold text-gray-900 mt-2">8</p>
                    </div>
                    <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                      <i className="fas fa-book-open text-blue-600 text-xl"></i>
                    </div>
                  </div>
                </div>
                
                <div className="bg-white rounded-xl shadow-lg p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">已完成课程</p>
                      <p className="text-3xl font-bold text-gray-900 mt-2">5</p>
                    </div>
                    <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                      <i className="fas fa-check-circle text-green-600 text-xl"></i>
                    </div>
                  </div>
                </div>
                
                <div className="bg-white rounded-xl shadow-lg p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">平均完成率</p>
                      <p className="text-3xl font-bold text-gray-900 mt-2">85%</p>
                    </div>
                    <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                      <i className="fas fa-chart-line text-purple-600 text-xl"></i>
                    </div>
                  </div>
                </div>
                
                <div className="bg-white rounded-xl shadow-lg p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">获得证书</p>
                      <p className="text-3xl font-bold text-gray-900 mt-2">3</p>
                    </div>
                    <div className="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                      <i className="fas fa-certificate text-yellow-600 text-xl"></i>
                    </div>
                  </div>
                </div>
              </div>
            </section>

            {/* 最近学习 */}
            <section className="mb-8">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-2xl font-bold text-gray-900">最近学习</h2>
                <Link to="/enrolled-courses" className="text-blue-600 hover:text-blue-700 font-medium">
                  查看全部 <i className="fas fa-arrow-right ml-1"></i>
                </Link>
              </div>
              <div className="bg-white rounded-xl shadow-lg p-6">
                <div className="space-y-4">
                  <div 
                    className="flex items-center space-x-4 p-4 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                    onClick={() => handleRecentCourseClick('course1')}
                  >
                    <img 
                      src="https://s.coze.cn/image/vvjKCww2aME/" 
                      alt="Python编程基础课程封面" 
                      className="w-16 h-12 object-cover rounded-lg" 
                    />
                    <div className="flex-1">
                      <h3 className="font-medium text-gray-900">Python编程基础</h3>
                      <div className="flex items-center space-x-4 mt-2">
                        <div className="flex items-center space-x-2">
                          <div className="w-24 h-2 bg-gray-200 rounded-full">
                            <div className="w-3/4 h-2 bg-blue-600 rounded-full"></div>
                          </div>
                          <span className="text-gray-600 text-sm">75%</span>
                        </div>
                        <span className="text-gray-600 text-sm">上次学习: 2024-01-15</span>
                      </div>
                    </div>
                    <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm">
                      继续学习
                    </button>
                  </div>
                  
                  <div 
                    className="flex items-center space-x-4 p-4 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                    onClick={() => handleRecentCourseClick('course2')}
                  >
                    <img 
                      src="https://s.coze.cn/image/1wQHrh_QJJw/" 
                      alt="数据分析与可视化课程封面" 
                      className="w-16 h-12 object-cover rounded-lg" 
                    />
                    <div className="flex-1">
                      <h3 className="font-medium text-gray-900">数据分析与可视化</h3>
                      <div className="flex items-center space-x-4 mt-2">
                        <div className="flex items-center space-x-2">
                          <div className="w-24 h-2 bg-gray-200 rounded-full">
                            <div className="w-1/2 h-2 bg-blue-600 rounded-full"></div>
                          </div>
                          <span className="text-gray-600 text-sm">50%</span>
                        </div>
                        <span className="text-gray-600 text-sm">上次学习: 2024-01-14</span>
                      </div>
                    </div>
                    <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm">
                      继续学习
                    </button>
                  </div>
                </div>
              </div>
            </section>

            {/* 功能中心 */}
            <section className="mb-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">功能中心</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <Link to="/personal-info" className="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition-all cursor-pointer">
                  <div className="text-center">
                    <div className="w-16 h-16 bg-blue-100 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <i className="fas fa-user-edit text-blue-600 text-2xl"></i>
                    </div>
                    <h3 className="font-semibold text-gray-900 mb-2">个人信息</h3>
                    <p className="text-gray-600 text-sm">查看和修改个人基本信息</p>
                  </div>
                </Link>
                
                <Link to="/enrolled-courses" className="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition-all cursor-pointer">
                  <div className="text-center">
                    <div className="w-16 h-16 bg-green-100 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <i className="fas fa-book-open text-green-600 text-2xl"></i>
                    </div>
                    <h3 className="font-semibold text-gray-900 mb-2">我的课程</h3>
                    <p className="text-gray-600 text-sm">管理已报名的所有课程</p>
                  </div>
                </Link>
                
                <Link to="/messages" className="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition-all cursor-pointer">
                  <div className="text-center">
                    <div className="w-16 h-16 bg-purple-100 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <i className="fas fa-envelope text-purple-600 text-2xl"></i>
                    </div>
                    <h3 className="font-semibold text-gray-900 mb-2">站内信</h3>
                    <p className="text-gray-600 text-sm">查看系统通知和消息</p>
                  </div>
                </Link>
                
                <Link to="/account-security" className="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition-all cursor-pointer">
                  <div className="text-center">
                    <div className="w-16 h-16 bg-yellow-100 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <i className="fas fa-shield-alt text-yellow-600 text-2xl"></i>
                    </div>
                    <h3 className="font-semibold text-gray-900 mb-2">账户安全</h3>
                    <p className="text-gray-600 text-sm">管理账户安全设置</p>
                  </div>
                </Link>
              </div>
            </section>

            {/* 学习统计 */}
            <section>
              <h2 className="text-2xl font-bold text-gray-900 mb-6">学习统计</h2>
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-white rounded-xl shadow-lg p-6">
                  <h3 className="font-semibold text-gray-900 mb-4">本周学习时长</h3>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-gray-600">周一</span>
                      <div className="flex items-center space-x-2 flex-1 mx-4">
                        <div className="w-full h-2 bg-gray-200 rounded-full">
                          <div className="w-3/4 h-2 bg-blue-600 rounded-full"></div>
                        </div>
                        <span className="text-gray-900 font-medium">2.5小时</span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-gray-600">周二</span>
                      <div className="flex items-center space-x-2 flex-1 mx-4">
                        <div className="w-full h-2 bg-gray-200 rounded-full">
                          <div className="w-1/2 h-2 bg-blue-600 rounded-full"></div>
                        </div>
                        <span className="text-gray-900 font-medium">1.5小时</span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-gray-600">周三</span>
                      <div className="flex items-center space-x-2 flex-1 mx-4">
                        <div className="w-full h-2 bg-gray-200 rounded-full">
                          <div className="w-full h-2 bg-blue-600 rounded-full"></div>
                        </div>
                        <span className="text-gray-900 font-medium">3.0小时</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div className="bg-white rounded-xl shadow-lg p-6">
                  <h3 className="font-semibold text-gray-900 mb-4">学习成就</h3>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="text-center p-4 bg-blue-50 rounded-lg">
                      <div className="text-2xl font-bold text-blue-600 mb-1">15</div>
                      <p className="font-medium text-gray-900">连续学习天数</p>
                      <p className="text-gray-600 text-sm">保持学习习惯</p>
                    </div>
                    <div className="text-center p-4 bg-green-50 rounded-lg">
                      <div className="text-2xl font-bold text-green-600 mb-1">120</div>
                      <p className="font-medium text-gray-900">总学习时长</p>
                      <p className="text-gray-600 text-sm">累计学习时间</p>
                    </div>
                    <div className="text-center p-4 bg-purple-50 rounded-lg">
                      <div className="text-2xl font-bold text-purple-600 mb-1">850</div>
                      <p className="font-medium text-gray-900">获得积分</p>
                      <p className="text-gray-600 text-sm">学习积分奖励</p>
                    </div>
                    <div className="text-center p-4 bg-yellow-50 rounded-lg">
                      <div className="text-2xl font-bold text-yellow-600 mb-1">92%</div>
                      <p className="font-medium text-gray-900">学习活跃度</p>
                      <p className="text-gray-600 text-sm">本周活跃度</p>
                    </div>
                  </div>
                </div>
              </div>
            </section>
          </div>
        </main>
      </div>
    </Layout>
  );
};

export default PersonalCenter;

